package cn.zzf.service.impl;

import cn.zzf.bean.User;
import cn.zzf.bean.UserLog;
import cn.zzf.service.UserLogService;
import cn.zzf.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Date;

/**
 * @author GaoFeng2017
 * @date 2018-07-01 15:20:18
 **/

@Service
public class UserTestServiceImpl implements cn.zzf.service.UserTestService {

    @Autowired
    private UserService userService;

    @Autowired
    private UserLogService userLogService;

    /**
     * required，spring默认事务方式，如果当前方法的调用者存在事务，则加入到调用者的事务中，否则为当前方法新建一个事务
     * @author GaoFeng
     * @date 2018/7/1 10:32
     * @param
     * @return void
     *
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void requiredTest() {
        userService.add(new User("张三",2000));
        userService.add(new User("李四",1000));
//        throw new RuntimeException();
    }

    /**
     * 不管调用者是否存在事务，都会创建新的事务，并且调用者的事务回滚不会影响当前方法的事务，而当前方法的事务回滚也不会影响调用者
     * @author GaoFeng
     * @date 2018/7/1 14:05
     * @param
     * @return void
     *
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void requiredNewTest() {
        userService.add(new User("王五",2000));
        userService.add(new User("赵六",1000));
        userService.update(new User("李四",3000,79));
        userService.updateNewException(new User("张三",500,7));
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void nestedTest() {
        userService.add(new User("钱七",100000));
        try{
            userService.insertNestedException(new User("孙八",1000));
        } catch (Exception e) {
            e.printStackTrace();
        }

        userService.insertNested(new User("庄九",28000));
        throw new RuntimeException();
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void orderTest() {
        userService.insertNested(new User("刘志超",2000000));
        userLogService.add(new UserLog(new Date(System.currentTimeMillis()),"用户刘志超下单"));
        //其他操作
    }
}

